package com.lzzy.web.Controller;


import com.lzzy.model.domain.Article;
import com.lzzy.model.domain.Comment;
import com.lzzy.service.impl.ArticleServicelmpl;
import com.lzzy.service.impl.CommentServicelmpl;
import com.lzzy.service.impl.FriendsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class ClientController {

    @Autowired
    private ArticleServicelmpl articleServicelmpl;

    @Autowired
    private CommentServicelmpl commentServicelmpl;

    @Autowired
   private FriendsServiceImpl friendsService;

    //分页
    //分页展示文章
    @GetMapping("/page/{page}")
    public String page(@PathVariable("page") int page, Model model) {
        int size = 5;
        Page<Article> articles = articleServicelmpl.pageArticle(page - 1, size);
        model.addAttribute("page", page);
        model.addAttribute("totalPage", articles.getTotalPages());
        model.addAttribute("articles", articles.getContent());
        return "client/index";
    }

    //跳转到首页
    @GetMapping("/index")
    public String testModel(Model model) {
        //调用分页方法
        return page(1, model);
    }

    //跳转到文章详情页
    @GetMapping("/article/{id}")
    public String article(@PathVariable("id") int id, Model model) {
        Article article = articleServicelmpl.findArticleById(id);

        //评论
        List<Comment> comments = commentServicelmpl.findcommentbyArticleid(id);
        model.addAttribute("article", article);

        model.addAttribute("comments", comments);
        return "client/article";
    }
    //添加评论
    @PostMapping("/article/{id}/comment")
    public String comment(@PathVariable("id") int id, @RequestParam("author") String author, @RequestParam("content") String content) {
        commentServicelmpl.addComment(id, author, content);
        return "redirect:/article/" + id;
    }

    //进入友链

    @GetMapping("/client/friends")
    public String friendsModel(Model model) {

        model.addAttribute("f",friendsService.findAll());
        return "client/friend";
    }


    //添加友链
    @PostMapping("/client/friend/add")
    public String comment(@RequestParam("friendsname") String friendsname, @RequestParam("email") String email,@RequestParam("link") String link) {
        friendsService.addFriend(friendsname,email,link);
        return "redirect:/client/friends";
    }


}
